package sa4

import javax.servlet.http._
import scala.xml._
import scala.collection.JavaConversions._
import scala.util.matching.Regex
import javax.servlet.ServletConfig
import scala.collection.mutable.HashMap
import scala.xml.transform._
import scala.xml.Null // hide scala.Null
import sa4.routing._
import sa4.sessions._

object responseBuilder {

  def builder(req: HttpServletRequest, resp: HttpServletResponse) {

    var path = req.getRequestURI()
    var flag = false;
    for (key <- GET.GETmap) {
      var regularKey = (key._1).r
      path match {
        case regularKey(path) => key._2._1(createParameterMAP(key._2._2, Seq(path)), req, resp); flag = true;
        case regularKey(path @ _*) => key._2._1(createParameterMAP(key._2._2, path), req, resp); flag = true;
        //TODO: correct bug with...you know what  - nice way to make me forget what we were talking about
        case _ =>
      }
    }

    for (key <- POST.POSTmap) {
      var regularKey = (key._1).r
      path match {
        case regularKey(path) => key._2._1(createParameterMAP(key._2._2, Seq(path)), req, resp); flag = true;
        case regularKey(path @ _*) => key._2._1(createParameterMAP(key._2._2, path), req, resp); flag = true;
        //TODO: correct bug with...you know what  - nice way to make me forget what we were talking about
        case _ =>
      }
    }

    if (!flag) {
      resp.getWriter.write(new PrettyPrinter(72, 2).formatNodes(xml.XML.loadFile(System.getProperty("user.dir") + "/html/" + "defaultError.html")))
    }
  }

  def createParameterMAP(ids: Seq[String], parameters: Seq[String]): HashMap[String, String] = {
    var parametersMap = new HashMap[String, String]
    if (ids.length > 0) {
      var param = parameters
      var value = param.head;

      //  parametersMap = (ids.zip(parameters)) to Map

      for (key <- ids) {
        value = param.head
        parametersMap(key) = value
        param = param.tail

      }
    }
    return parametersMap
  }

}